<template>
  <BasicModal
    title="新增"
    width="60%"
    v-bind="$attrs"
    destroyOnClose
    @register="registerDrawer"
    showFooter
    @ok="handleSubmit"
  >
    <div class="ml-1 pt-2">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { useMessage } from '/@/hooks/web/useMessage';

  import { tabSchemas } from './data';

  export default defineComponent({
    name: 'PlusTabPageModal',
    components: { BasicModal, BasicForm },

    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();

      const [registerForm, { setProps, resetFields, validate, updateSchema }] = useForm({
        rowProps: { gutter: 16 },
        labelWidth: 110,
        baseColProps: { lg: 12, md: 23 },
        // schemas: tabSchemas,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        const schemas = tabSchemas(data.pageType, data.client);
        setProps({
          schemas,
        });
        updateSchema({
          field: 'value',
          rules: [
            {
              validator(_, value) {
                const isExist = data.modelList.find((el) => el.value === value);
                if (isExist) return Promise.reject('标签编码不能重复');

                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
        });
      });

      async function handleSubmit() {
        try {
          const values = await validate();

          // if(modelList)
          setModalProps({ confirmLoading: true });
          const params = Object.assign(values, {});
          createMessage.success('操作成功', 0.8);
          closeModal();
          emit('success', params);
          return;
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        handleSubmit,
        // treeData,
      };
    },
  });
</script>
